package com.bpz.jxw.user.controller;

import com.alibaba.fastjson.JSON;
import com.bpz.jxw.user.annotation.CheckLogin;
import com.bpz.jxw.user.model.User;
import com.bpz.jxw.user.service.IUserService;
import com.bpz.jxw.user.service.impl.UserService;
import com.bpz.main.bean.ImgInfo;
import com.bpz.main.bean.ReturnValueType;
import com.bpz.main.model.ActMsg;
import com.bpz.utils.ImageUtils;
import com.bpz.utils.PropCnfg;
import com.bpz.utils.SessionUtils;
import com.bpz.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 半瓶子 on 1/24/15.
 * blog: xusir.cnblogs.com
 */
@Controller
@RequestMapping("user")
public class UserCtrl {

    @Autowired
    IUserService userService;

    @ResponseBody
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String login(@RequestParam(value = "username", required = true) String username, @RequestParam(value = "password", required = true) String password) {
        ActMsg msg = userService.login(username, password);
        return JSON.toJSONString(msg);
    }

    @RequestMapping(value = "loginout", method = RequestMethod.GET)
    public void loginout(HttpServletResponse response) throws IOException {
        SessionUtils.getInstance().remove("user_session");
        response.sendRedirect("/");
    }

    @ResponseBody
    @RequestMapping(value = "reg", method = RequestMethod.POST)
    public String reg(@RequestParam(value = "username", required = true) String username, @RequestParam(value = "password", required = true) String password, @RequestParam(value = "email", required = true) String email) {
        ActMsg msg = userService.reg(username, password, email);
        return JSON.toJSONString(msg);
    }

    @RequestMapping(value = "talk")
    public ModelAndView talk(HttpServletRequest request) throws UnsupportedEncodingException {
        ModelAndView view = new ModelAndView("main");
        view.addObject("template", "/include/talk.html");
        SessionUtils session = SessionUtils.getInstance();
        request.setCharacterEncoding("utf-8");

        Object o = session.get("tipData");
        if (o != null) {
            view.addObject("tipData", o);
            session.remove("tipData");
        }
        return view;
    }

    @RequestMapping(value = "talk", method = RequestMethod.POST)
    @CheckLogin(returnValue = ReturnValueType.Action, url = "/user/talk")
    public void talk(@RequestParam(value = "pic", required = false) MultipartFile pic, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String content = request.getParameter("content");
        String video = request.getParameter("video");
        String tag = request.getParameter("tag");
        String is_anonymous = request.getParameter("is_anonymous");
        String jokeType = request.getParameter("jokeType");
        int isAnonymous = 0;
        if (!StringUtils.isEmpty(is_anonymous)) {
            isAnonymous = Integer.parseInt(is_anonymous);
        }
        User user = UserService.getLoginUser();
        ImgInfo img = new ImgInfo();
        ActMsg msg = new ActMsg();
        msg.setCode(ActMsg.ERROR);
        boolean flag = true;
        int type=1;
        if (!pic.isEmpty()) {
            Long size = pic.getSize();
            if (size > 1024*1024 * 2) {
                msg.setMsg(MessageFormat.format(PropCnfg.getVal("imgSizeBigger"), 2));
                flag = false;
            }else{
                InputStream is=pic.getInputStream();
                BufferedImage bi= ImageIO.read(is);
                img.setWidth(bi.getWidth());
                img.setHeight(bi.getHeight());
                img.setName(pic.getOriginalFilename());
                img.setPath( "resources/Uploads/Images/"+ img.getName());
                // 文件保存路径
                String filePath = request.getSession().getServletContext().getRealPath("/") + img.getPath();
                ImageUtils.pressText3("见笑网",bi,filePath,"黑体",36, Color.gray,80,0,0,0.7f);
                type=2;
            }
        }
        if (!StringUtils.isEmpty(video))
        {
            type=3;
        }
        if (flag) {
            msg = userService.talk(user.getUid(), content, video, tag, isAnonymous, img,type);
        }
        if(msg.getCode()!=ActMsg.SUCCESS) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("content", content);
            map.put("tag", tag);
            map.put("video", video);
            map.put("isAnonymous", isAnonymous);
            map.put("jokeType", jokeType);
            msg.setData(map);
            SessionUtils.getInstance().set("tipData", msg);
        }
        response.sendRedirect("talk");
    }

}
